package com.hmal.geteway.filter;

import com.hmal.geteway.config.AuthProperties;
import com.hmal.geteway.utils.JwtTool;
import com.hmall.common.utils.CollUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author wuJiaWei
 * @version 1.0
 */

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否需要做登录拦截
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }
        //3.获取token
        String token = "";
        List<String> headers = request.getHeaders().get("authorization");
        if(!CollUtils.isEmpty(headers)){
            token = headers.get(0);
        }else{
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //4.校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        // 5.如果有效，传递用户信息
        String userInfo = userId.toString();
        exchange.mutate()
                .request(builder -> builder.header("user-info",userInfo))
                        .build();
        // 6.放行
        return chain.filter(exchange);
    }

    private boolean isExclude(String string) {
        if (string == null || authProperties == null || authProperties.getExcludePaths() == null) {
            return false;
        }
        return authProperties.getExcludePaths().stream().anyMatch(path -> antPathMatcher.match(path, string));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}